package com.gdk.ksoft.ui.reporters;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.assembly.dbhelper.FfindGoodsDbHelper;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.CxqhGoodsTable;
import com.gdk.ksoft.data.entry.tables.CxqhSaleDetailTable;
import com.gdk.ksoft.data.entry.tables.CxqhSaleTable;
import com.gdk.ksoft.ui.reporters.adapters.GoodsAdapter;
import com.gdk.ksoft.assembly.dialog.FixCxqhDialog;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.utils.extensions.ControlUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemLongClick;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 车销请货页面
 */
public class CxqhActivity extends Activity {

    public static final int REQ_CODE_FIND_GOODS = 0x0001;//查找商品数据的请求码
    @ViewInject(R.id.pcxqh_lstOrders)private ListView listOrders;//商品清单列表
    @ViewInject(R.id.pcxqh_txtGoodsCount)private TextView txtGoodsCount;//商品总数
    @ViewInject(R.id.pcxqh_txtGoodsKinds)private TextView txtGoodsKinds;//商品种类

    private List<HashMap<String,Object>> goodslist = new ArrayList<>();//商品列表
    private GoodsAdapter goodsAdapter;//商品数据适配器
    private DbUtils dbUtils;//数据库操作对象

    public static final int MSG_REMAKE_ACCOUNT = 0X0001;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(MSG_REMAKE_ACCOUNT == msg.what){
                executeMakeAccountTask(goodslist);//统计商品数据
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cxqh);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        goodsAdapter = new GoodsAdapter(this,goodslist);
        listOrders.setAdapter(goodsAdapter);
        listOrders.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                final HashMap<String,Object> item = goodslist.get(position);
                int intJs = Integer.parseInt(item.get("js").toString());
                int intSs = Integer.parseInt(item.get("ss").toString());
                final int intHsgx = Integer.parseInt(item.get("sp_hsgx").toString());
                new FixCxqhDialog(CxqhActivity.this,intJs,intSs,intHsgx,new FixCxqhDialog.OnValueChangedListener() {
                    @Override
                    public void onPriceChange(int js, int ss) {
                        try {
                            //修改列表中的数据
                            item.put("js", js+ss/intHsgx);
                            item.put("ss", ss%intHsgx);
                            goodslist.set(position, item);//修改商品列表数据
                            goodsAdapter.notifyDataSetChanged();
                            executeMakeAccountTask(goodslist);//统计商品信息
                            //把本地数据库的数据也修改了
                            CxqhGoodsTable citem = new CxqhGoodsTable();
                            citem.id = Integer.parseInt(item.get("data_id").toString());//赋值数据ID
                            citem.js = js+ss/intHsgx;//赋值件数
                            citem.ss = ss%intHsgx;//赋值散数
                            citem.sp_id = Integer.parseInt(item.get("sp_id").toString());//赋值商品ID
                            dbUtils.update(citem, "js", "ss");//修改本地商品数据
                            ControlUtils.showToast(CxqhActivity.this,"修改成功!",Gravity.CENTER,Toast.LENGTH_SHORT);
                        }catch (Exception e){
                            e.printStackTrace();
                            ControlUtils.showToast(CxqhActivity.this,"修改失败!",Gravity.CENTER,Toast.LENGTH_SHORT);
                        }
                    }
                }).show();
            }
        });
        executeQueryAllCartGoods(this,dbUtils);//加载购物车的商品
    }

    /**
     * 列表项长按点击事件
     * @param parent
     * @param view
     * @param position
     * @param id
     * @return
     */
    @OnItemLongClick(value={R.id.pcxqh_lstOrders})
    public boolean onItemLongClick(AdapterView<?> parent, View view,final int position, long id) {
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("确定删除该商品吗?");
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                if(v.getId() == MessageBox.ID_DIALOG_BUTTON_OK){
                    try{
                        HashMap<String,Object> item = goodslist.get(position);
                        int id = Integer.parseInt(item.get("data_id").toString());
                        goodslist.remove(position);//删除第几项
                        goodsAdapter.notifyDataSetChanged();//刷新界面
                        dbUtils.deleteById(CxqhGoodsTable.class,id);
                        ControlUtils.showToast(CxqhActivity.this,"删除成功!",Gravity.CENTER,Toast.LENGTH_SHORT);
                        executeMakeAccountTask(goodslist);//统计商品数据
                    }catch (Exception e){
                        e.printStackTrace();
                        ControlUtils.showToast(CxqhActivity.this,"删除失败!",Gravity.CENTER,Toast.LENGTH_SHORT);
                    }
                }
            }
        });
        msgBox.show();
        return true;
    }

    /**
     * 界面控件点击事件
     * @param v
     */
    @OnClick(value={R.id.pcxqh_txtFindGoods,R.id.pcxqh_txtSubmit,R.id.pcxqh_imgClearOrder})
    public void onClick(View v){
        switch(v.getId()){
            case R.id.pcxqh_txtFindGoods://查找商品
                Intent intent = new Intent(this,CxqhFindActivity.class);
                startActivityForResult(intent,REQ_CODE_FIND_GOODS);//运行到查找商品的页面
                break;
            case R.id.pcxqh_txtSubmit://确认请货
                if(listOrders.getChildCount()<=0){
                    ControlUtils.showToast(this,"当前没有商品可请货，请添加商品!",Gravity.CENTER,Toast.LENGTH_SHORT);
                    return;
                }
                if(!NetworkUtils.isNetAvailable(this)){
                    ControlUtils.showToast(this,"当前网络不可用,请检查您的网络!", Gravity.CENTER, Toast.LENGTH_SHORT);
                    return;
                }
                final MessageBox tipDialog = new MessageBox(this);
                tipDialog.setMessage("请在网络畅通的情况下上传数据，该数据需要实时上传!");
                tipDialog.onPositiveNegitiveClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tipDialog.dismiss();
                        if(v.getId() == MessageBox.ID_DIALOG_BUTTON_OK){
                            executeUploadCxqhTask(CxqhActivity.this,dbUtils);//上传请单数据
                        }
                    }
                });
                tipDialog.show();
                break;
            case R.id.pcxqh_imgClearOrder://清空列表数据
                if(listOrders.getChildCount()<=0) return;//无效操作
                final MessageBox msgBox = new MessageBox(this);
                msgBox.setMessage("确定清空所有商品数据么？");
                msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        msgBox.dismiss();
                        if(v.getId() == MessageBox.ID_DIALOG_BUTTON_OK){
                            try {
                                dbUtils.deleteAll(CxqhGoodsTable.class);
                                txtGoodsCount.setText("0件0散");
                                txtGoodsKinds.setText("0种");
                                //清空界面数据
                                goodslist.clear();
                                goodsAdapter.notifyDataSetChanged();
                                ControlUtils.showToast(CxqhActivity.this,"清空完成!", Gravity.CENTER, Toast.LENGTH_SHORT);
                            }catch (Exception e){
                                e.printStackTrace();
                                ControlUtils.showToast(CxqhActivity.this,"清空失败，发生错误!", Gravity.CENTER, Toast.LENGTH_SHORT);
                            }
                        }
                    }
                });
                msgBox.show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQ_CODE_FIND_GOODS && resultCode == Activity.RESULT_OK){
            executeQueryAllCartGoods(this,dbUtils);//查询所有购物车商品
        }
    }

    /**
     * 查询所有购物车商品
     */
    public void executeQueryAllCartGoods(final Context context,final DbUtils dbUtils){
        new AsyncTask<Void,Void,Void>(){
            private String errMessage;
            private ProgressDialog dialog;
            private List<HashMap<String,Object>> goodslist;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    goodslist = FfindGoodsDbHelper.findAllCxqhGoodsInCart(dbUtils);
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    ControlUtils.showToast(context,"加载数据失败!",Gravity.CENTER,Toast.LENGTH_SHORT);
                    return;
                }
                //清空列表中的原数据
                CxqhActivity.this.goodslist.clear();
                CxqhActivity.this.goodsAdapter.notifyDataSetChanged();
                if(goodslist!=null && goodslist.size()>0){//如果有数据则添加到列表中
                    CxqhActivity.this.goodslist.addAll(goodslist);//添加所有商品项
                    CxqhActivity.this.goodsAdapter.notifyDataSetChanged();
                    CxqhActivity.this.listOrders.setSelection(0);
                }
                handler.sendEmptyMessage(MSG_REMAKE_ACCOUNT);//通知统计商品信息
            }
        }.execute();
    }

    /**
     * 统计商品数据
     */
    public void executeMakeAccountTask(final List<HashMap<String,Object>> goodslist){
        if(goodslist == null || goodslist.size()<=0){
            txtGoodsCount.setText("0件0散");
            txtGoodsKinds.setText("0种");
            return;
        }
        new AsyncTask<Void,Void,Void>(){
            private int intJs = 0,//件数数量
                    intSs = 0,//散数数量
                    intKinds = 0;//种类数量
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    List<Integer> kinds = new ArrayList<Integer>();
                    for (HashMap<String, Object> item : goodslist) {
                        intJs += Integer.parseInt(item.get("js").toString());
                        intSs += Integer.parseInt(item.get("ss").toString());
                        int intSpId = Integer.parseInt(item.get("sp_id").toString());
                        if (kinds.contains(intSpId)) continue;//如果已经包含该产品
                        kinds.add(intSpId);
                    }
                    intKinds = kinds.size();//获取种类数量
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                txtGoodsCount.setText(intJs + "件" + intSs + "散");
                txtGoodsKinds.setText(intKinds + "种");
            }
        }.execute();
    }

    /**
     * 执行提交车销请货单的任务
     * @param context
     * @param dbUtils
     */
    public void executeUploadCxqhTask(final Context context,final DbUtils dbUtils){
        new AsyncTask<Void,Void,Void>(){//提交请货清单数据
            private ProgressDialog dialog;
            private String errMessage;
            private String orderNo;//请货单号
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在提交数据...");
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    orderNo = requestCxqhOrder();//获取车销请单数据
                    if(!TextUtils.isEmpty(orderNo)){
                        uploadCxqhOrder(dbUtils,orderNo,goodslist);//上传车销请单数据
                    }else{
                        errMessage = "上传数据失败,请重试!";
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    ControlUtils.showToast(context,"网络错误，上传车销请单失败!",Gravity.CENTER,Toast.LENGTH_SHORT);
                }else{
                    try {
                        txtGoodsCount.setText("0件0散");
                        txtGoodsKinds.setText("0种");
                        //清空界面数据
                        goodslist.clear();
                        goodsAdapter.notifyDataSetChanged();
                        //显示提示信息
                        ControlUtils.showToast(context, "上传车销请单数据成功!", Gravity.CENTER, Toast.LENGTH_SHORT);
                        //显示请货单单号
                        final MessageBox msgBox = new MessageBox(context);
                        msgBox.setMessage("单号：" + orderNo);
                        msgBox.txtCancel.setVisibility(View.GONE);
                        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                msgBox.dismiss();
                            }
                        });
                        msgBox.show();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }.execute();
    }

    /**
     * 请求车销请货单号
     * @return
     */
    public String requestCxqhOrder()throws Exception{
        RequestParams params = new RequestParams("UTF-8");
        String methodName = "Cx_DbdDjh";
        String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}";
        System.out.println("-----> 获取车销请单单号数据：" + messageBody);
        params.addBodyParameter("Method", methodName);
        params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
        params.addBodyParameter("MessageBody", messageBody);
        InputStream is = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
        String result = FileUtils.stream2string(is, "UTF-8");
        System.out.println("------->获取车销请单单号的结果是："+result);
        if (!TextUtils.isEmpty(result)) {
            BaseResultModel resultModel = new Gson().fromJson(result,BaseResultModel.class);
            if(resultModel!=null && resultModel.Result.equals("0000")) {
                return resultModel.Data;
            }
        }
        return null;
    }

    /**
     * 上传车销请单数据
     * @throws Exception
     */
    public void uploadCxqhOrder(final DbUtils dbUtils,String orderNo,List<HashMap<String,Object>> data)throws Exception{
        List<GoodsEntry> goodsList = convertHashMapListToGoodsEntryList(data);//获取需要上传的商品的数据
        RequestParams params = new RequestParams("UTF-8");
        String methodName = "Cx_UpDbd";
        String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI
                + "\",\"Data\":{\"xsd\":{\"djh\":\"" + orderNo+"\"}, \"xsdsps\":"
                + new Gson().toJson(goodsList) + "}}";
        System.out.println("-----> 上传车销请单单号数据：" + messageBody);
        params.addBodyParameter("Method", methodName);
        params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
        params.addBodyParameter("MessageBody", messageBody);
        InputStream is = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
        String result = FileUtils.stream2string(is, "UTF-8");
        System.out.println("------->上传车销请单单号的结果是："+result);
        if (!TextUtils.isEmpty(result)) {
            BaseResultModel resultModel = new Gson().fromJson(result,BaseResultModel.class);
            if(resultModel!=null && resultModel.Result.equals("0000")) {
                SQLiteDatabase database = dbUtils.getDatabase();
                database.beginTransaction();
                try {
                    CxqhSaleTable cxqhSaleTable = new CxqhSaleTable();//车销请单数据
                    cxqhSaleTable.djh = orderNo;//设置单据号
                    int totalJs = 0, totalSs = 0;//总件数及总散数
                    for (HashMap<String, Object> item : data) {
                        CxqhSaleDetailTable cxqhSaleDetailTable = new CxqhSaleDetailTable();
                        cxqhSaleDetailTable.sp_id = Integer.parseInt(item.get("sp_id").toString());
                        cxqhSaleDetailTable.js = Integer.parseInt(item.get("js").toString());
                        cxqhSaleDetailTable.ss = Integer.parseInt(item.get("ss").toString());
                        cxqhSaleDetailTable.djh = orderNo;//输入单据号，用以关联
                        totalJs += cxqhSaleDetailTable.js;
                        totalSs += cxqhSaleDetailTable.ss;
                        dbUtils.save(cxqhSaleDetailTable);
                    }
                    cxqhSaleTable.js = totalJs;
                    cxqhSaleTable.ss = totalSs;
                    cxqhSaleTable.qdrq = new Date().toString();
                    dbUtils.save(cxqhSaleTable);//添加车销请单到数据库
                    //清空本地购物车数据内容
                    dbUtils.deleteAll(CxqhGoodsTable.class);
                    database.setTransactionSuccessful();
                }catch(Exception e){
                    e.printStackTrace();
                }finally {
                    database.endTransaction();
                }
            }else{
                throw new Exception("网络错误，上传车销请单失败");
            }
        }else{
            throw new Exception("网络错误，上传车销请单失败");
        }
    }

    /**
     * 转换HashMap集合到GoodsEntry集合
     * @param data
     * @return
     */
    public List<GoodsEntry> convertHashMapListToGoodsEntryList(List<HashMap<String,Object>> data){
        if(data == null || data.size()<=0) return null;
        List<GoodsEntry> glist = new ArrayList<>();
        for(HashMap<String,Object> item : data){
            GoodsEntry goodsItem = new GoodsEntry();
            goodsItem.hsdwsl = Integer.parseInt(item.get("js").toString())//件数
                    *Integer.parseInt(item.get("sp_hsgx").toString())//换算关系
                    +Integer.parseInt(item.get("ss").toString());//散数数量
            goodsItem.sp_id = Integer.parseInt(item.get("sp_id").toString());
            glist.add(goodsItem);
        }
        return glist;
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pcxqh_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 需要上传的商品的实例
     */
    public class GoodsEntry{
        /**
         * 商品ID
         */
        public int sp_id;
        /**
         * 商品最小单位数量
         */
        public int hsdwsl;
    }


}
